<template>
  <div class="container">
    <div class="ui-upload-video" v-if="authProgress < 100">
      <el-upload
        :before-upload="handleBeforeUpload"
        :action="host"
        accept=".mp4,.flv,.mov,.mp3"
      >
        <el-button class="ui-video-box">
          <el-icon class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-button>
      </el-upload>
      <span v-if="file">
        <el-button
          type="primary"
          :loading="Loading"
          style="font-size: 12px"
          @click="authUpload"
          >{{ Loading ? $t("key1055") : $t("key1056") }}</el-button
        >
        <div class="status">
          {{ $t("key1054") }}: <span>{{ statusText || $t("key130") }}</span>
        </div>
        <el-progress
          :percent="authProgress"
          :stroke-color="['#108ee9', '#87d068']"
        />
      </span>
    </div>
    <div class="upload" v-if="authProgress == 100">
      <div
        class="prism-player"
        id="J_prismPlayer"
        style="width: 260px; height: 180px; display: inline-block"
      >
        <!--<Spin fix v-if="loadingState">-->
        <!--  <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>-->
        <!--  <div>Loading</div>-->
        <!--</Spin>-->
      </div>
      <el-button
        type="primary"
        :loading="Loading"
        style="margin-top: -28px; font-size: 12px; margin-left: 22px"
        @click="reselectFn"
        >{{ $t("key1053") }}
      </el-button>
      <!--      <div>-->
      <!--        <input type="file" id="fileUpload" @change="fileChange($event)">-->
      <!--        <label class="status">上传状态: <span>{{statusText}}</span></label>-->
      <!--      </div>-->
      <!--      <div class="upload-type">-->
      <!--        上传方式一, 使用 UploadAuth 上传:-->
      <!--        <button @click="authUpload" :disabled="uploadDisabled">开始上传</button>-->
      <!--        <button @click="pauseUpload" :disabled="pauseDisabled">暂停</button>-->
      <!--        <button :disabled="resumeDisabled" @click="resumeUpload">恢复上传</button>-->
      <!--        <span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i> %</span>-->
      <!--      </div>-->
    </div>
    <!--    <div class="info">uploadAuth及uploadAddress参数请查看<a href="https://help.aliyun.com/document_detail/55407.html" target="_blank">获取上传地址和凭证</a></div>-->
  </div>
</template>
<script>
import service from "../../utils/system/request";
// import Setting from '@/setting';
import { Delete, Plus, ZoomIn } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";

export default {
  components: {
    Plus
  },
  data() {
    return {
      loadingState: false,
      timeout: "",
      partSize: "",
      parallel: "",
      retryCount: "",
      retryDuration: "",
      region: "cn-shanghai",
      userId: "1303984639806000",
      file: null,
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: "",
      Loading: false,
      // host: import.meta.env.VITE_BASE_URL,
      host: "http://admin.ufutx.net/", // https://love.ufutx.com/
      playerId: "aliplayer_" + Math.random().toString(36).substr(2),
      scriptTagStatus: 0,
      isReload: false,
      instance: null,
      isRect: false,
      importTimeV2: null,
      uploadNum: 0, // 循环十次
      reset: false
    };
  },
  mounted() {
    console.log(this.host, "====");
    // var player = new Aliplayer({
    //     id: 'J_prismPlayer',
    //     width: '100%',
    //     autoplay: false,
    //     // 支持播放地址播放,此播放优先级最高
    //     source: 'https://act.mcake.com/fangli/2018/pc/zhou-nian/video/zhounian-7.mp4'
    //     // // 播放方式二：点播用户推荐
    //     // vid: '1e067a2831b641db90d570b6480fbc40',
    //     // playauth: '',
    //     // cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png',
    //     // // 播放方式三：仅MPS用户使用
    //     // vid: '1e067a2831b641db90d570b6480fbc40',
    //     // accId: '',
    //     // accSecret: '',
    //     // stsToken: '',
    //     // domainRegion: '',
    //     // authInfo: '',
    //     // // 播放方式四：使用STS方式播放
    //     // vid: '1e067a2831b641db90d570b6480fbc40',
    //     // accessKeyId: '',
    //     // securityToken: '',
    //     // accessKeySecret: ''
    //     // isLive: true
    //     // // getCurrentTime: _this.aaaa
    // }, function (player) {
    //     console.log('播放器创建好了。')
    // });
  },
  methods: {
    reselectFn() {
      this.authProgress = 0;
      this.statusText = "";
      this.file = null;
      this.isRect = true;
      clearInterval(this.importTimeV2);
      this.importTimeV2 = null;
      this.reset = true;
      this.loadingState = false;
      this.uploadNum = 0;
    },
    // 文件上传
    handleBeforeUpload(file) {
      if (
        [
          "video/mp4",
          "video/mp3",
          "audio/mpeg",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb"
        ].indexOf(file.type) === -1
      ) {
        ElMessage.warning("请上传正确的视频格式");
        return false;
      }
      this.file = file;
      // this.$Notice.info({
      //   title: '温馨提示',
      //   duration: 2,
      //   desc: `${this.file.name} 准备上传`
      // });
      this.imgName = file.name;
      this.isRect = false;
      this.fileChange();
      return false;
    },
    fileChange(e) {
      console.log(this.host);
      // this.file = e.target.files[0]
      if (!this.file) {
        // this.$Notice.error('请先选择需要上传的文件!')
        return;
      }
      var Title = this.file.name;
      var userData = '{"Vod":{}}';
      if (this.uploader) {
        this.uploader.stopUpload();
        this.authProgress = 0;
        this.statusText = "";
      }
      this.uploader = this.createUploader();
      console.log(userData);
      this.uploader.addFile(this.file, null, null, null, userData);
      this.uploadDisabled = false;
      this.pauseDisabled = true;
      this.resumeDisabled = true;
    },
    authUpload() {
      // 然后调用 startUpload 方法, 开始上传
      if (!this.file) {
        // this.$Message.error('请先选择需要上传的文件!')
        return;
      }
      this.Loading = true;
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.uploadDisabled = true;
        this.pauseDisabled = false;
      }
    },
    // 暂停上传
    pauseUpload() {
      if (this.uploader !== null) {
        this.uploader.stopUpload();
        this.resumeDisabled = false;
        this.pauseDisabled = true;
      }
    },
    // 恢复上传
    resumeUpload() {
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.resumeDisabled = true;
        this.pauseDisabled = false;
      }
    },
    createUploader(type) {
      let self = this;
      let uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 60000,
        partSize: self.partSize || 1048576,
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        region: self.region,
        userId: self.userId,
        // 添加文件成功
        addFileSuccess: function (uploadInfo) {
          self.uploadDisabled = false;
          self.resumeDisabled = false;
          self.statusText = "添加文件成功, 等待上传...";
          console.log("addFileSuccess: " + uploadInfo.file.name);
        },
        // 开始上传
        onUploadstarted: function (uploadInfo) {
          // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
          // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
          // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
          // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
          // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
          if (!uploadInfo.videoId) {
            // let createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
            console.log(uploadInfo, "939111");
            let data = {
              file_name: uploadInfo.file.name
              // cover_url: 'https://images.ufutx.com/test.png'
            };
            axios
              .post(`${self.host}/api/admin/create/upload/video`, data)
              .then(({ data }) => {
                console.log(data);
                data = data.data;
                let uploadAuth = data.UploadAuth;
                let uploadAddress = data.UploadAddress;
                let videoId = data.VideoId;
                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  uploadAuth,
                  uploadAddress,
                  videoId
                );
              });
            self.statusText = "文件开始上传...";
            // console.log(
            //   "onUploadStarted:" +
            //     uploadInfo.file.name +
            //     ", endpoint:" +
            //     uploadInfo.endpoint +
            //     ", bucket:" +
            //     uploadInfo.bucket +
            //     ", object:" +
            //     uploadInfo.object
            // );
          } else {
            // 如果videoId有值，根据videoId刷新上传凭证
            // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
            let refreshUrl = `${self.host}/api/admin/refresh/upload/video?VideoId=${uploadInfo.videoId}`;
            axios.get(refreshUrl).then(({ data }) => {
              console.log(data);
              data = data.data;
              let uploadAuth = data.UploadAuth;
              let uploadAddress = data.UploadAddress;
              let videoId = data.VideoId;
              uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAuth,
                uploadAddress,
                videoId
              );
            });
          }
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
          console.log(uploadInfo, "uploadInfo");
          // console.log(
          //   "onUploadSucceed: " +
          //     uploadInfo.file.name +
          //     ", endpoint:" +
          //     uploadInfo.endpoint +
          //     ", bucket:" +
          //     uploadInfo.bucket +
          //     ", object:" +
          //     uploadInfo.object
          // );
          self.statusText = "文件上传成功!";
          self.Loading = false;
          console.log(uploadInfo.videoId);
          self.loadingState = true;
          self.importTimeV2 = setInterval(() => {
            if (!self.reset) {
              axios
                .get(
                  `${self.host}/api/admin/video/url?aliyun_video_id=${uploadInfo.videoId}`
                )
                .then(res => {
                  if (res.data.message === "视频审核中,请稍后重试") {
                    self.uploadNum++;
                    // this.onUploadSucceed(uploadInfo)
                  } else {
                    let { play_url } = res.data.data;
                    // let videoImg = play_url + '?x-oss-process=video/snapshot,t_1000,m_fast,w_800'
                    clearInterval(self.importTimeV2);
                    self.importTimeV2 = null;
                    self.loadingState = false;
                    self.uploadNum = 0;
                    self.$emit("uploadVideoFn", uploadInfo.videoId, play_url);
                    var player = new Aliplayer(
                      {
                        id: "J_prismPlayer",
                        width: "100%",
                        autoplay: false,
                        source: play_url
                      },
                      function (player) {
                        console.log("播放器创建好了。");
                      }
                    );
                  }
                })
                .catch(() => {
                  console.log("出错了~");
                });
            }
          }, 2000);
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
          // console.log(
          //   "onUploadFailed: file:" +
          //     uploadInfo.file.name +
          //     ",code:" +
          //     code +
          //     ", message:" +
          //     message
          // );
          self.statusText = "文件上传失败!";
          self.Loading = false;
        },
        // 取消文件上传
        onUploadCanceled: function (uploadInfo, code, message) {
          // console.log(
          //   "Canceled file: " +
          //     uploadInfo.file.name +
          //     ", code: " +
          //     code +
          //     ", message:" +
          //     message
          // );
          self.statusText = "文件已暂停上传";
          self.Loading = false;
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
          // console.log(
          //   "onUploadProgress:file:" +
          //     uploadInfo.file.name +
          //     ", fileSize:" +
          //     totalSize +
          //     ", percent:" +
          //     Math.ceil(progress * 100) +
          //     "%"
          // );
          let progressPercent = Math.ceil(progress * 100);
          self.authProgress = progressPercent;
          self.statusText = "文件上传中...";
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          let refreshUrl =
            `${self.host}/api/admin/refresh/upload/video?VideoId=` +
            uploadInfo.videoId;
          axios.get(refreshUrl).then(({ data }) => {
            let uploadAuth = data.UploadAuth;
            uploader.resumeUploadWithAuth(uploadAuth);
            console.log(
              "upload expired and resume upload with uploadauth " + uploadAuth
            );
          });
          self.statusText = "文件超时...";
        },
        // 全部文件上传结束
        onUploadEnd: function (uploadInfo) {
          console.log("onUploadEnd: uploaded all the files");
          self.statusText = "文件上传完毕";
        }
      });
      return uploader;
    }
  }
};
</script>
<style lang="postcss" scoped>
@import "https://g.alicdn.com/de/prismplayer/2.7.2/skins/default/aliplayer-min.css";

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

.demo-spin-icon-load-1 {
  width: 200px;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.ui-upload-video {
}

.ui-video-box {
  width: 143px;
  height: 88px;
  line-height: 87px;
  float: left;
  //margin-right: 22px;
}

.ui-video-box .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 85px;
  line-height: 85px;
  border-radius: 6px;
  text-align: center;
  margin-right: 22px;
  border: 1px dashed #c0ccda;
}

:deep(.el-upload .el-button--small) {
  padding: 0;
}
</style>
